# 本文件处理一些数据相关的内容吧
from database.dbop import Database
import database.sql as Sql
import src.global_config as gl
import src.tool as tool
import hashlib
import sqlite3


class Data_Center:
    db = None
    data_set_path = None
    model = None

    def __init__(self):
        self.db = Database()
        self.data_set_path = gl.get_value('dbpath')
        # self.db.init(gl.get_value('dbpath'))
        self.model = gl.get_value('model')

    # 查询棋谱库
    def get_goban(self):
        sql = Sql.select_go_data
        data = self.db.select(sql)
        return data

    # 保存棋谱
    def save_goban(self, sgf, additional):
        createTime = tool.getCurrentTimeStr()
        black = additional['PB']
        white = additional['PW']
        blackRank = additional['BR']
        whiteRank = additional['WR']
        komi = additional['KM']
        platform = additional['AP']
        rule = additional['RU']
        result = additional['RE']
        playDate = additional['DT']
        readTime = '0'
        md5 = tool.getMd5(sgf)
        sql = Sql.insert_go_data.format(sgf, black, white, blackRank, whiteRank, result, createTime, readTime,
                                        playDate,
                                        komi, platform, rule, md5)
        self.db.insert(sql, False)
        return {
            'code': 0,
            'message': '保存棋谱成功'
        }

    def check_file_name(self, name):
        sql = Sql.select_file_read.format(name)
        data = self.db.select(sql)
        return data

    def count_go_data(self):
        sql = Sql.select_count_go_data
        data = self.db.select(sql)
        return data

    def save_checked_name(self, name):
        sql = Sql.insert_file_read.format(name)
        data = self.db.insert(sql, True)
        return data

    def vacuum(self):
        self.db.vacuum()

    # 删除围棋数据集合 慎用!!!
    def delete_go_data(self):
        delete1 = Sql.delete_go_data
        delete2 = Sql.delete_file_name
        self.db.delete(delete1)
        self.db.delete(delete2)
        self.vacuum()

    # ai old current Tom
    # 传入以上四种名称 返回数据
    def get_model_by_name(self, name):
        path = self.model[name]
        if path is None:
            print("未配置{}数据库地址".format(name))
            return []
        self.db.init(path)
        res = self.db.select(Sql.select_go_data)
        return res

    def get_all_data_set(self):
        res = []
        # try:
        print("model地址列表:",self.model)
        res.extend(self.get_model_by_name('current'))
        res.extend(self.get_model_by_name('old'))
        res.extend(self.get_model_by_name('Tom'))
        res.extend(self.get_model_by_name('ai'))
        print("总计{}条数据".format(len(res)))
        # except sqlite3.OperationalError:
        #     print("数据库打开失败")
        return res